<template>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
        <el-row :gutter="20">
          <!--输入框-->
          <el-col :span="8">
            <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
        <!--表格-->
        <el-table :data="userList" style="width: 100%" border>
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="#" width="55"></el-table-column>
          <el-table-column prop="username" label="姓名" width="120"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
          <el-table-column prop="mobile"  label="电话" width="180"></el-table-column>
          <el-table-column prop="role_name"  label="角色" width="180"></el-table-column>
          <el-table-column prop="mg_state" label="状态" >
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="userStatusChange(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" icon="el-icon-edit"  @click="showEditDialog(scope.row.id)"></el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeUserById(scope.row.id)"></el-button>
              <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRoles(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="pageSizes"
          :page-size="queryInfo.pagesize"
          :layout="layout"
          :total="total">
        </el-pagination>
      </el-card>
      <!--修改窗-->
      <el-dialog  title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!--编辑窗-->
      <el-dialog  title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
          <el-form-item label="用户名称" >
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" ></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile" >
            <el-input v-model="editForm.mobile" ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog title="分配角色" :visible.sync="rolesDialogVisible" width="50%" @close="roleDialogClose">
        <div>
          <p>当前用户：{{userInfo.username}}</p>
          <p>当前角色：{{userInfo.role_name}}</p>
          <p>分配角色：
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
    <el-button @click="rolesDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
      </el-dialog>

    </div>
</template>

<script>
    export default {
      data() {
        return {
          queryInfo: {
            query: '', // 查询参数
            pagenum: 1, // 当前页码
            pagesize: 2 //  每页显示条数
          },
          pageSizes: [2, 5, 10, 20],
          layout: 'total, sizes, prev, pager, next, jumper',
          userList: [],
          total: 0, // 总条数
          addDialogVisible: false,
          editDialogVisible: false,
          editForm: {},
          addForm: {
            username: '',
            password: '',
            email: '',
            mobile: ''
          },
          // 添加验证规则
          addFormRules: {
            username: [
              { required: true, message: '用户名不能为空', trigger: 'blur' }
            ],
            password: [
              { required: true, message: '密码不能为空', trigger: 'blur' },
              { min: 6, max: 18, message: '长度在 6 - 18 个字符', trigger: 'blur' }
            ],
            email: [
              { required: true, message: '邮箱不能为空', trigger: 'blur' },
              { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ],
            mobile: [
              { required: true, message: '电话不能为空', trigger: 'blur' },
              {pattern: /^1[12345789]\d{9}$/, message: '请输入正确的手机号码'}
            ]
          },
          // 编辑验证规则
          editFormRules: {
            email: [
              { required: true, message: '邮箱不能为空', trigger: 'blur' },
              { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ],
            mobile: [
              { required: true, message: '电话不能为空', trigger: 'blur' },
              {pattern: /^1[12345789]\d{9}$/, message: '请输入正确的手机号码'}
            ]
          },
          rolesDialogVisible: false,
          userInfo: {}, // 需要分配角色信息
          rolesList: [], // 所以角色数据表
          selectedRoleId: ''// 以选中的角色ID值
        }
      },
      created() {
        this.getUserList()
      },
      methods: {
        async getUserList() {
          const {data: res} = await this.$http.get('users', {
            params: this.queryInfo
          });
          if (res.meta.status !== 200) return this.$message.error({message: res.msg});
          console.log(res)
          this.userList = res.data.users
          this.total = res.data.total
        },
        handleSizeChange(newSize) {
          console.log(newSize)
          this.queryInfo.pagesize = newSize
          this.getUserList()
        },
        handleCurrentChange(newPage) {
          console.log(newPage)
          this.queryInfo.pagenum = newPage
          this.getUserList()
        },
        async userStatusChange(userInfo) {
          const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
          if (res.meta.status !== 200) {
            this.userList.mg_state = !this.userList.mg_state;
            return this.$message.error({message: res.msg});
          }
          this.$message.success({message: '更新成功！'})
        },
        addDialogClose() { // 监听添加对话框关闭事件
          this.$refs.addFormRef.resetFields();
        },
        /* 添加用户 */
        addUser() {
          this.$refs.addFormRef.validate(async valid => {
            if (!valid) return; // 判断校验是否通过
            const {data: res} = await this.$http.post('users', this.addForm);
            if (res.meta.status !== 201) return this.$message.error({message: '添加用户失败！'});
            this.$message.success({message: '添加用户成功！'});
            // 关闭对话框
            this.addDialogVisible = false;
            this.getUserList();
          })
        },
        /* 编辑用户 */
        async showEditDialog(id) {
          const {data: res} = await this.$http.get('users/' + id);
          if (res.meta.status !== 200) return this.$message.error({message: '查询用户信息失败！'});
          console.log(res)
          this.editForm = res.data;
          this.editDialogVisible = true;
        },
        // 监听编辑对话框关闭事件
        editDialogClose() {
          this.$refs.editFormRef.resetFields();
        },
        // 更新用户
        editUserInfo() {
          this.$refs.editFormRef.validate(async valid => {
            // 判断校验是否通过
            if (!valid) return;

            const {data: res} = await this.$http.put('users/' + this.editForm.id,
              {
                email: this.editForm.email,
                mobile: this.editForm.mobile
              });
            if (res.meta.status !== 200) return this.$message.error({message: '更新用户失败！'});
            // 关闭对话框
            this.editDialogVisible = false;
            this.getUserList();
            this.$message.success({message: '更新用户成功！'});
          })
        },
        // 根据id删除用户
        async removeUserById(id) {
         const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err);
          // 确定返回字符串 confirm ，取消返回字符串 cancel
          if (confirmResult === 'cancel') {
            return this.$message.info('已经取消删除！');
          }
          console.log('确定删除')
          const {data: res} = await this.$http.delete('users/' + id)
          if (res.meta.status !== 200) return this.$message.error({message: '删除用户失败！'});
          this.$message.success({message: '删除用户成功！'});
          this.getUserList();
        },
        // 获取角色
        async setRoles(userInfo) {
          this.userInfo = userInfo;
          const {data: res} = await this.$http.get('roles');
          if (res.meta.status !== 200) return this.$message.error({message: '获取角色列表失败！'})
          this.rolesList = res.data;
          this.rolesDialogVisible = true
        },
        // 更新角色
        async saveRoleInfo() {
          if (!this.selectedRoleId) {
           return this.$message.error('还没选择角色！')
          }
          const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`, {
            rid: this.selectedRoleId
          });
          if (res.meta.status !== 200) return this.$message.error({message: '更新角色失败！'});
          this.$message.success({message: '更新角色成功！'});
          this.getUserList();
          this.rolesDialogVisible = false
        },
        // 监听角色对话框关闭事件
        roleDialogClose() {
          this.selectedRoleId = '';
          this.userInfo = []
        }

      }
    }
</script>

<style scoped>

</style>
